﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Data.SqlClient;

namespace TCCT_CTC_CSDLDangVienV1.DanhMuc
{
    public partial class frmTuDien : frmBase
    {
        /// <summary>
        /// Từ điển ID
        /// </summary>
        public string SelectedID = string.Empty;
        public string SelectedTen = string.Empty;
        private string MaDanhMuc = string.Empty;
        public bool IsFormFind = false;
        public string SelectedDauMoiID = "";

        public frmTuDien()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="maDanhMuc"></param>
        /// <param name="TenDanhMuc">Tên danh mục từ điển</param>
        public frmTuDien(string maDanhMuc, string TenDanhMuc)
        {

            InitializeComponent();
            this.MaDanhMuc = maDanhMuc;
            this.Text = TenDanhMuc;
        }

        private void frmTuDien_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsFormFind)
                    SelectedDauMoiID = MyCommon.CurrentUserDauMoiID;//khi mở form tìm kiếm thì dầu mối được gửi từ dưới lên

                MySetCurentDauMoi();

                ApplyUI();



                if (!gTimKiemThongTin.Enabled)
                {
                    gCapNhatThongTin.Enabled = false;
                    return;
                }
                BindDataToControl();

                BindDataToGrid();

                if (SelectedID != string.Empty)
                {
                    dgData.SetFocusedNode(dgData.FindNodeByFieldValue("TuDienID", SelectedID));
                }

            }
            catch (Exception _ex)
            {
                ShowErrorMessage(_ex);
            }
        }

        /// <summary>
        /// Hàm gán text thể hiện người dùng đang làm việc với danh mục của đơn vị nào
        /// Trước khi gọi hàm này thì bạn phải xác định và gán trước giá trị cho biến SelectedDauMoiID
        /// </summary>
        private void MySetCurentDauMoi()
        {
            try
            {
                gTimKiemThongTin.Text = "Tìm kiếm F3 - Đơn vị hiện tại: " + SqlHelper.ExecuteScalar(CommandType.Text, "Select TenDV From tblDau_Moi Where ID = " + SelectedDauMoiID);
            }
            catch (Exception _ex)
            {
                gTimKiemThongTin.Text = "Tìm kiếm F3 - Đơn vị hiện tại: Không xác định";
                MyCommon.ShowMessage(_ex.Message);
            }
        }
        //Nơi gán thuộc tính giao diện cho các control
        private void ApplyUI()
        {
            UI.Button.ApplyInsert(btnThemMoi);
            UI.Button.ApplyInsert(btnThemVaoNodeHienTai);
            UI.Button.ApplyUpdate(btnSuaDoi);

            UI.Button.ApplyDelete(btnXoaBo);
            UI.Button.ApplyClose(btnThoat);
            UI.Button.ApplyAccept(btnChapNhan);
            UI.Button.ApplyExportExcel(btnXuatExcel);

            if (IsFormFind)
            {
                btnChonDonVi.Visible = false;
                gCapNhatThongTin.Enabled = false;
                gCapNhatThongTin.Visible = false;
                dgData.Columns["CapNhatCuoi"].Visible = false;
                dgData.Columns["CreateDate"].Visible = false;
                dgData.Columns["UpdateDate"].Visible = false;
            }
            else
                btnChapNhan.Visible = false;

            UI.TextBox.ApplyFind(txtTenGoiFind);

            this.dgData.Columns["CreateDate"].Format.FormatType = DevExpress.Utils.FormatType.DateTime;
            this.dgData.Columns["CreateDate"].Format.FormatString = MyConst.FORMAT_DATETIME.ddMMyyyyHHmmss;

            this.dgData.Columns["UpdateDate"].Format.FormatType = DevExpress.Utils.FormatType.DateTime;
            this.dgData.Columns["UpdateDate"].Format.FormatString = MyConst.FORMAT_DATETIME.ddMMyyyyHHmmss;



        }


        //Nơi tải dữ liệu danh mục lên các control để lựa chọn: ví dụ: Combobox, listbox ...
        private void BindDataToControl()
        {
        }

        //Nơi tải dữ liệu lên grid chứa dữ liệu
        private void BindDataToGrid()
        {
            try
            {
                string sql = "Select DM.ID, DM.ID As TuDienID, DM.ParentID, DM.TenGoi, (Select Top 1 IsNull(HoTen,'') As HoTen From tblUser Where ID=DM.UserID And DauMoiID=DM.ID) As CapNhatCuoi,CapTren, DM.CreateDate, DM.UpdateDate " +
                          "From tblTuDien DM " +
                          "Where Deleted=0 And MaDanhMuc=@MaDanhMuc And DM.ID=" + SelectedDauMoiID + " Order By DM.TenGoi ";
                List<SqlParameter> arrParameters = new List<SqlParameter>();
                arrParameters.Add(SqlHelper.CreateParameterObject("@MaDanhMuc", SqlDbType.NVarChar, ParameterDirection.Input, MaDanhMuc));

                dgData.DataSource = SqlHelper.ExecuteDataTable(CommandType.Text, sql, arrParameters);

            }
            catch (Exception _ex)
            {
                ShowErrorMessage(_ex);
            }
        }

        private void btnThemMoi_Click(object sender, EventArgs e)
        {
            SqlTransaction MyTran = SqlHelper.BeginTransaction();
            try
            {
                frmInputBox ff = new frmInputBox();
                ff.Text = "Them moi danh muc";
                ff.lblLoiNhac.Text = "Nhập tên danh mục mới";
                ff.txtKetQua.Text = "";
                bool MyTranCommited = false;
                if (ff.ShowDialog() == DialogResult.OK)
                {

                    string sql = "Insert Into tblTuDien(TuDienID, ParentID, DauMoiID, TenGoi, MaDanhMuc, CapTren,  UserID, CreateDate) Values(@TuDienID, @ParentID, @DauMoiID, @TenGoi, @MaDanhMuc, @CapTren, @UserID, GetDate()); ";
                    sql += "Select Max(ID) From tblTuDien ";

                    List<SqlParameter> arrParameters = new List<SqlParameter>();

                    object MaxTuDienID = SqlHelper.ExecuteScalar(MyTran, CommandType.Text, "Select Max(TuDienID) From tblTuDien Where MaDanhMuc='" + MaDanhMuc + "' And DauMoiID='" + SelectedDauMoiID + "' ");

                    int iMaxTuDienID = 0;
                    if (MaxTuDienID != null)
                        iMaxTuDienID = Util.ToInt(MaxTuDienID.ToString()) + 1;
                    arrParameters.Add(SqlHelper.CreateParameterObject("@TuDienID", SqlDbType.Int, ParameterDirection.Input, iMaxTuDienID));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@ParentID", SqlDbType.Int, ParameterDirection.Input, dgData.Nodes.Count == 0 ? "" : dgData.FocusedNode.GetValue("ParentID")));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@DauMoiID", SqlDbType.Int, ParameterDirection.Input, SelectedDauMoiID));

                    arrParameters.Add(SqlHelper.CreateParameterObject("@TenGoi", SqlDbType.NVarChar, ParameterDirection.Input, ff.txtKetQua.Text.Trim()));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@MaDanhMuc", SqlDbType.NVarChar, ParameterDirection.Input, MaDanhMuc));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@CapTren", SqlDbType.NVarChar, ParameterDirection.Input, ""));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, MyCommon.CurrentUserID));
                    int maxID = Util.ToInt(SqlHelper.ExecuteScalar(MyTran, CommandType.Text, sql, arrParameters));

                    sql = "Update tblTuDien Set CapTren=@CapTren, SynCode=1 Where ID=@ID ";
                    arrParameters = new List<SqlParameter>();

                    arrParameters.Add(SqlHelper.CreateParameterObject("@CapTren", SqlDbType.NVarChar, ParameterDirection.Input, ";" + iMaxTuDienID + ";"));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@ID", SqlDbType.Int, ParameterDirection.Input, maxID));

                    SqlHelper.ExecuteNonQuery(MyTran, CommandType.Text, sql, arrParameters);
                    MyTran.Commit();
                    MyTranCommited = true;
                    BindDataToGrid();

                }
                if (!MyTranCommited)
                    MyTran.Commit();
            }
            catch (Exception _ex)
            {
                MyTran.Rollback();
                ShowErrorMessage(_ex);
            }
        }

        private void btnSuaDoi_Click(object sender, EventArgs e)
        {
            SqlTransaction MyTran = SqlHelper.BeginTransaction();
            try
            {
                frmInputBox ff = new frmInputBox();
                ff.Text = "Sua doi danh muc";
                ff.lblLoiNhac.Text = "Nhập tên danh mục mới";
                ff.txtKetQua.Text = "";
                bool MyTranCommited = false;
                if (ff.ShowDialog() == DialogResult.OK)
                {
                    string sql = "Update tblTuDien Set TenGoi=@TenGoi, UserID=@UserID, UpdateDate=GetDate(), SynCode=1 Where ID=@ID; ";
                    List<SqlParameter> arrParameters = new List<SqlParameter>();

                    arrParameters.Add(SqlHelper.CreateParameterObject("@TenGoi", SqlDbType.NVarChar, ParameterDirection.Input, ff.txtKetQua.Text.Trim()));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, MyCommon.CurrentUserID));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@ID", SqlDbType.Int, ParameterDirection.Input, dgData.FocusedNode.GetValue("ID").ToString()));

                    SqlHelper.ExecuteNonQuery(MyTran, CommandType.Text, sql, arrParameters);
                    MyTran.Commit();
                    MyTranCommited = true;
                    BindDataToGrid();

                }
                if (!MyTranCommited)
                    MyTran.Commit();
            }
            catch (Exception _ex)
            {
                MyTran.Rollback();
                ShowErrorMessage(_ex);
            }
        }

        private bool IsInvalid()
        {
            bool isValid = true;
            ValidationMessage = null;
            AppendValidationMessage("Bạn cần nhập dữ liệu cho: ");
            //if (txtTenGoi.EditValue.ToString().Trim() == "")
            //{
            //    AppendValidationMessage("Tên gọi");
            //    isValid = false;
            //}
            //Hiện thông báo lỗi khi isValid=false
            if (!isValid)
                ShowValidationMessage();

            return isValid;
        }

        private void btnLuu_Click(object sender, EventArgs e)
        {
            //try
            //{
            //    if (!IsInvalid())
            //        return;

            //    if (Action == MyConst.ACTION.Insert)
            //    {
            //        string sql = "Insert Into tblTuDien(TenGoi, CreateDate, UserID, MaDanhMuc) " +
            //            "Values (@TenGoi, GetDate(), @UserID, @MaDanhMuc)";
            //        List<SqlParameter> arrParameters = new List<SqlParameter>();
            //        arrParameters.Add(SqlHelper.CreateParameterObject("@TenGoi", SqlDbType.NVarChar, ParameterDirection.Input, txtTenGoi.Text.Trim()));
            //        arrParameters.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.BigInt, ParameterDirection.Input, Common.CurrentUserID));
            //        arrParameters.Add(SqlHelper.CreateParameterObject("@MaDanhMuc", SqlDbType.NVarChar, ParameterDirection.Input, MaDanhMuc));
            //        SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParameters);

            //    }
            //    else
            //    {
            //        string sql = "Update tblTuDien Set TenGoi=@TenGoi, UpdateDate=GetDate(), UserID=@UserID " +
            //           "Where ID=@ID ";
            //        List<SqlParameter> arrParameters = new List<SqlParameter>();
            //        arrParameters.Add(SqlHelper.CreateParameterObject("@TenGoi", SqlDbType.NVarChar, ParameterDirection.Input, txtTenGoi.Text.Trim()));
            //        arrParameters.Add(SqlHelper.CreateParameterObject("@ID", SqlDbType.BigInt, ParameterDirection.Input, SelectedID));
            //        arrParameters.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.BigInt, ParameterDirection.Input, Common.CurrentUserID));
            //        SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParameters);

            //    }

            //    BindDataToGrid();

            //    ResetValues(gCapNhatThongTin);

            //    Action = MyConst.ACTION.Insert;
            //    Common.ShowMessage("Lưu dữ liệu thành công");
            //}
            //catch (Exception _ex)
            //{
            //    ShowErrorMessage(_ex);
            //}
        }


        private void btnThoat_Click(object sender, EventArgs e)
        {
            try
            {
                this.DialogResult = DialogResult.Cancel;
                this.Close();
            }
            catch (Exception _ex)
            {
                ShowErrorMessage(_ex);
            }
        }

        private void txtTenGoiFind_EditValueChanged(object sender, EventArgs e)
        {
            try
            {

                ((DataTable)dgData.DataSource).DefaultView.RowFilter = "TenGoi Like '%" + txtTenGoiFind.Text.Trim() + "%' ";
            }
            catch (Exception _ex)
            {
                ShowErrorMessage(_ex);
            }
        }

        private void txtTenGoiFind_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Down)
                    dgData.Focus();
            }
            catch (Exception _ex)
            {
                ShowErrorMessage(_ex);
            }
        }

        private void btnChapNhan_Click(object sender, EventArgs e)
        {
            try
            {
                if (dgData.Selection.Count == 0)
                {
                    ShowInfoMessage("Không có kết quả nào được tìm thấy");
                    return;
                }

                if (IsFormFind)
                {
                    this.SelectedID = dgData.FocusedNode.GetValue("TuDienID").ToString();
                    this.SelectedTen = GetString(dgData, "TenGoi");
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
            }
            catch (Exception _ex)
            {
                ShowErrorMessage(_ex);
            }
        }

        //Nếu phím là enter và Action=Find thì có nghĩa là chấp nhận kết quả tìm kiếm.
        private void dgData_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnChapNhan_Click(null, null);
            }
        }

        private void menuThemMoi_Click(object sender, EventArgs e)
        {
            if (btnThemMoi.Enabled)
                btnThemMoi_Click(null, null);
        }

        private void menuSuaDoi_Click(object sender, EventArgs e)
        {
            if (btnSuaDoi.Enabled)
                btnSuaDoi_Click(null, null);
        }

        private void menuLuu_Click(object sender, EventArgs e)
        {
            if (btnSuaDoi.Enabled)
                btnLuu_Click(null, null);
        }

        private void menuXoaBo_Click(object sender, EventArgs e)
        {
            if (btnXoaBo.Enabled)
                btnXoaBo_Click(null, null);
        }

        private void menuTimKiem_Click(object sender, EventArgs e)
        {
            ResetValues(gTimKiemThongTin);
            txtTenGoiFind.Focus();
        }

        private void menuChapNhan_Click(object sender, EventArgs e)
        {
            btnChapNhan_Click(null, null);
        }

        private void btnXuatExcel_Click(object sender, EventArgs e)
        {
            try
            {
                TreeListExportToExcel(dgData);
            }
            catch (Exception _ex)
            {
                ShowErrorMessage(_ex);
            }
        }

        private void txtTenGoi_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                e.Handled = true;

            }
        }

        private void btnThemVaoNodeHienTai_Click(object sender, EventArgs e)
        {
            if (dgData.FocusedNode == null)
            {
                MyCommon.ShowMessage("Bạn cần chọn một tên danh mục làm cấp trên");
                return;
            }
            SqlTransaction MyTran = SqlHelper.BeginTransaction();
            try
            {
                frmInputBox ff = new frmInputBox();
                ff.Text = "Them moi danh muc";
                ff.lblLoiNhac.Text = "Nhập tên danh mục mới";
                ff.txtKetQua.Text = "";
                bool MyTranCommited = false;
                if (ff.ShowDialog() == DialogResult.OK)
                {
                    string sql = "Insert Into tblTuDien(TuDienID, DauMoiID, ParentID, TenGoi, MaDanhMuc, CapTren, UserID, CreateDate) Values(@TuDienID, @DauMoiID, @ParentID, @TenGoi, @MaDanhMuc, @CapTren, @UserID, GetDate()); ";
                    sql += "Select Max(ID) From tblTuDien ";

                    List<SqlParameter> arrParameters = new List<SqlParameter>();

                    object MaxTuDienID = SqlHelper.ExecuteScalar(MyTran, CommandType.Text, "Select Max(TuDienID) From tblTuDien Where MaDanhMuc='" + MaDanhMuc + "' And DauMoiID='" + SelectedDauMoiID + "' ");

                    int iMaxTuDienID = 0;
                    if (MaxTuDienID != null)
                        iMaxTuDienID = Util.ToInt(MaxTuDienID.ToString()) + 1;
                    arrParameters.Add(SqlHelper.CreateParameterObject("@TuDienID", SqlDbType.Int, ParameterDirection.Input, iMaxTuDienID));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@DauMoiID", SqlDbType.Int, ParameterDirection.Input, SelectedDauMoiID));

                    arrParameters.Add(SqlHelper.CreateParameterObject("@ParentID", SqlDbType.Int, ParameterDirection.Input, dgData.FocusedNode.GetValue("TuDienID").ToString()));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@TenGoi", SqlDbType.NVarChar, ParameterDirection.Input, ff.txtKetQua.Text.Trim()));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@MaDanhMuc", SqlDbType.NVarChar, ParameterDirection.Input, MaDanhMuc));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@CapTren", SqlDbType.NVarChar, ParameterDirection.Input, ""));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, MyCommon.CurrentUserID));

                    int maxID = Util.ToInt(SqlHelper.ExecuteScalar(MyTran, CommandType.Text, sql, arrParameters));

                    sql = "Update tblTuDien Set CapTren=@CapTren, SynCode=1 Where ID=@ID ";
                    arrParameters = new List<SqlParameter>();

                    arrParameters.Add(SqlHelper.CreateParameterObject("@CapTren", SqlDbType.NVarChar, ParameterDirection.Input, dgData.FocusedNode.GetValue("CapTren").ToString() + iMaxTuDienID + ";"));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@ID", SqlDbType.Int, ParameterDirection.Input, maxID));

                    SqlHelper.ExecuteNonQuery(MyTran, CommandType.Text, sql, arrParameters);
                    MyTran.Commit();
                    MyTranCommited = true;
                    BindDataToGrid();

                }
                if (!MyTranCommited)
                    MyTran.Commit();
            }
            catch (Exception _ex)
            {
                MyTran.Rollback();
                ShowErrorMessage(_ex);
            }
        }


        private void btnXoaBo_Click(object sender, EventArgs e)
        {
            if (dgData.FocusedNode.Nodes.Count > 0)
            {
                MyCommon.ShowMessage("Bạn không thể xóa nút này vì còn có nút con cấp dưới. Chỉ có thể xóa khi một nút không có nút con");
                return;
            }

            try
            {
                if (ShowQuestionMessage("Bạn có chắc chắn xóa?") == DialogResult.Yes)
                {
                    string sql = "Update tblTuDien Set Deleted=1, UserID=@UserID, UpdateDate=GetDate(), SynCode=1 Where ID=@ID ";
                    List<SqlParameter> arrParameters = new List<SqlParameter>();


                    arrParameters = new List<SqlParameter>();
                    arrParameters.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, MyCommon.CurrentUserID));
                    arrParameters.Add(SqlHelper.CreateParameterObject("@ID", SqlDbType.Int, ParameterDirection.Input, dgData.FocusedNode.GetValue("ID").ToString()));

                    SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParameters);
                    dgData.Nodes.Remove(dgData.FocusedNode);
                }
            }
            catch (Exception _ex)
            {

                ShowErrorMessage(_ex);
            }
        }

        private void btnChonDonVi_Click(object sender, EventArgs e)
        {
            if (DanhMuc.frmDauMoiList.InstanceFind.ShowDialog() == DialogResult.OK)
            {
                this.SelectedDauMoiID = DanhMuc.frmDauMoiList.InstanceFind.SelectedID;

                if (SelectedDauMoiID != MyCommon.CurrentUserDauMoiID)
                {
                    menuStrip1.Enabled = false;
                    gCapNhatThongTin.Enabled = false;
                    gCapNhatThongTin.Visible = false;
                }
                else
                {
                    menuStrip1.Enabled = true;
                    gCapNhatThongTin.Enabled = true;
                    gCapNhatThongTin.Visible = true;
                }

                MySetCurentDauMoi();
                BindDataToGrid();
            }
        }

        private void dgData_DoubleClick(object sender, EventArgs e)
        {
            btnChapNhan_Click(null, null);
        }

        private void dgData_KeyDown_1(object sender, KeyEventArgs e)
        {
            if(e.KeyCode == Keys.Enter )
                btnChapNhan_Click(null, null);
        }





    }
}